package com.qdlc.p2p.manage.common.interceptor;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionInvocation;
import com.qdlc.p2p.biz.service.LogService;
import com.qdlc.p2p.biz.service.MenuService;
import com.qdlc.p2p.biz.web.interceptor.ActionInterceptor;
import com.qdlc.p2p.common.constant.Global;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.LogType;
import com.qdlc.p2p.common.util.ip.IPUtil;
import com.qdlc.p2p.dal.dto.Log;
import com.qdlc.p2p.dal.dto.Menu;
import com.qdlc.p2p.dal.dto.Operator;

public class ManageActionInterceptor extends ActionInterceptor {
    private static final long serialVersionUID = 1008901298342362080L;
    private static final Logger log = Logger.getLogger(ManageActionInterceptor.class);
    private static final String NONE = "";

    @Resource
    private LogService logService;

    @Resource
    private MenuService menuService;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Global.setIP(request);
        String actionName = invocation.getInvocationContext().getName();
        String className = invocation.getAction().getClass().getName();
        String url = request.getRequestURI();
        log.info("++++ class:" + className + ",url:" + url);
        
        try {
            // 权限校验
            Operator op = (Operator) request.getSession().getAttribute(Constant.SESSION_OPERATOR);
            if (op != null) {
                boolean flag = menuService.getMenuPermission(op.getId(), this.getManagePath());
                if (!flag) {
                    printJson("您没有此操作的权限！");
                    return null;
                }
            }

            String result = invocation.invoke();
            saveOperatorLog(className, actionName);
            return result;
        } catch (Exception e) {
            log.error(actionName, e);
            message(NONE, "系统异常联系管理员！");
            saveExceptionLog(className, actionName, e);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("result", false);
            data.put("msg", e.getMessage());
            printJson(JSON.toJSONString(data));
            return null;
        }
    }

    /**
     * 系统操作信息保存
     *
     * @param className  类命
     * @param methodName 方法名
     */
    public void saveOperatorLog(String className, String methodName) {
		HttpServletRequest request = ServletActionContext.getRequest();
        String path = request.getServletPath();
        String ip = "";
        try {
            ip = IPUtil.getRemoteIP(request);
        } catch (Exception e) {
            log.info("IP异常");
            e.printStackTrace();
        }

        boolean result = this.isOperatorLog(path);
        if (result) {
            Menu menu = menuService.getMenuByHref(path);
            Log log = new Log();
            log.setMethod(methodName);
            if (menu != null) {
                log.setException(menu.getRemark());
            }
            log.setParams(this.getAllParams(true));
            log.setRemoteAddr(ip);
            log.setRequestUri(path);
            log.setType(LogType.TYPE_OPERATOR);
            Operator op = (Operator) request.getSession().getAttribute(Constant.SESSION_OPERATOR);
            if (op != null) {
                log.setAddUser(op.getName());
                log.setException(log.getException() + ",系统操作员：" + op.getName() + ",账号：" + op.getUserName());
            }
            logService.addLog(log);
        }
    }

    public String getManagePath() {
		HttpServletRequest request = ServletActionContext.getRequest();
        String path = request.getServletPath();
        return path.replace(".action", ".html");
    }


    /**
     * 此次请求，是否保存操作日志信息
     *
     * @param path 路径
     * @return 结果
     */
    public boolean isOperatorLog(String path) {
        String[] urlArr = {"Add.action", "Edit.action", "Delete.action"};
        for (int i = 0; i < urlArr.length; i++) {
            String url = urlArr[i];
            int size = path.lastIndexOf(url);
            if (size > 0) {
                return true;
            }
        }
        return false;
    }
}
